package com.wwwc.index.web.servlet;

import java.io.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;
import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;
import com.wwwc.index.web.ejb.*;

public class UserHomeBean extends UserHomeManagerServlet {
    DecimalFormat td = new DecimalFormat("0.00");
    private EJBDatabaseQuery ejbdb;
    private String query = null;

    public StringBuffer getManager (String call_path, String mid, String sub_dir, String user_name, int user_level, int default_storage)
    {
	int total_usage   = 0;
	int added_storage = 0;
	int total_storage = user_level*default_storage;

	StringBuffer sbf = new StringBuffer("");
	try {
	    added_storage = getAddedStorageSize(mid, user_name, sub_dir);

	    if(added_storage >0) {
		total_storage = default_storage + added_storage;
	    }

	    if(added_storage <0) {
		return sbf.append("System error. Please try again.");
	    }

	    total_usage = getTotalStorageUsage(user_name, sub_dir);
	    if(total_usage <0) {
		return sbf.append("System error. Please try again.");
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:getManager:Error:"+e);
	    return sbf.append("System error. Please try again.");
	}

	sbf.append("\n<TABLE cellSpacing='0' cellPadding='0' border='0' width='100%' style='border-bottom:1px solid'>");
	sbf.append("\n<TR>");
	sbf.append("\n<TD align='center'>");
	sbf.append("<B>"+user_name.toUpperCase()+"'S/"+sub_dir+"</B>");
	sbf.append("</TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("<B>Total Usage:&nbsp;</B>["+td.format(total_usage/1000000.0)+"/"+total_storage/1000000+"]MB");

	if(total_usage >= total_storage) {
	    sbf.append("&nbsp;[<A href="+call_path+"?mid="+mid+"&aid="+addStorageCallBack+"><B>Add</B></A>]");
	}
	sbf.append("</TD>");
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");
	return sbf;
    }

    public int getAddedStorageSize (String mid, String user_name, String sub_dir) {
	int added_storage = 0;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    long ctime = System.currentTimeMillis();

	    String query = "SELECT SIZE FROM USER_STORAGE WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND MID="+mid+" AND END_TIME > "+ctime+";";
	   
	    Vector v = ejbdb.selectSingleFieldValueVector(query, "SIZE");
	    if(v != null && !v.isEmpty()) {
		Enumeration enum = v.elements();
		while(enum.hasMoreElements()) {
		    added_storage += Integer.parseInt((String)enum.nextElement());
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:getAddedStorageSize:Error:"+e);
	    added_storage = -1;
	}
	return added_storage;
    }

    public int getTotalStorageUsage (String user_name, String sub_dir) {
	int total_usage = 0;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    
	    String query = "SELECT * FROM USER_HOME WHERE USER_NAME='"+user_name+"' AND SUB_DIR='"+sub_dir+"' AND STATUS <>-1;";
	    ArrayList alist = ejbdb.select(query);

	    if(alist != null && !alist.isEmpty()) {
 		Iterator it = alist.iterator();
		ArrayList a = null;
		while (it.hasNext()) {
		    a = (ArrayList)it.next();
		    total_usage  += Long.parseLong(""+a.get(6));
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:getTotalStorageUsage:Error:"+e);
	    total_usage = -1;
	}
	return total_usage;
    }

    public StringBuffer getAddStorageOption (String call_path, String mid)
    {
	StringBuffer sbf = new StringBuffer("");
	sbf.append("<BR><BR><H3>You have no room to add new file</H3><BR>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<input type=submit name=B value='Add Storage' style='font-size:8pt'>");
	sbf.append("<input type=hidden name=mid value="+mid+">");
	sbf.append("<input type=hidden name=aid value="+addStorageCallBack+">");
	sbf.append("</FORM>");
	return sbf;
    }

    public ArrayList getSingleStoragePriceDetail (String mid, String id) {
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    
	    String query = "SELECT * FROM USER_STORAGE_PRICE WHERE MID="+mid+" AND ID="+id+";";
	    return (ejbdb.selectSingleRecord(query));
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:getSingleStoragePriceDetail:Error:"+e);
	    return null;
	}
    }

    public StringBuffer getActionBar (String call_path, String mid)
    {
	StringBuffer sbf = new StringBuffer("");
	sbf.append("\n<TABLE>");
	sbf.append("\n<TR><TD>"+MyHtml.makeLinkCell("Add Folder", call_path+"?mid="+mid+"&aid=1-1")+"</TD></TR>");	
	sbf.append("\n<TR><TD>"+MyHtml.makeLinkCell("Edit Folder", call_path+"?mid="+mid+"&aid=1-2")+"</TD></TR>");
	sbf.append("\n<TR><TD>"+MyHtml.makeLinkCell("Upload File", call_path+"?mid="+mid+"&aid=1-3")+"</TD></TR>");
	sbf.append("\n<TR><TD>"+MyHtml.makeLinkCell("E-mail Friends", call_path+"?mid="+mid+"&aid=1-4")+"</TD></TR>");	
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");
	return sbf;
    }

    public StringBuffer getUserFolders (String call_path, String mid, String sub_dir, String user_name)
    {
	StringBuffer sbf = new StringBuffer("<BR>");
	sbf.append("\n<TABLE>");

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    query = "SELECT ID, USER_DIR, TOTAL_FILES FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND STATUS <> -1 ORDER BY USER_DIR;";
	  
	    ArrayList alist = ejbdb.select(query);

	    Iterator it = alist.iterator();
	    ArrayList a = null;
	    String did = null;
	    String dir = null;
	    String tfs = null;
	    while (it.hasNext()) {
		a = (ArrayList)it.next();
		did = ""+a.get(0);
		dir = ""+a.get(1);
		tfs = ""+a.get(2);
		sbf.append("\n<TR><TD><A href='"+call_path+"?mid="+mid+"&aid=3&did="+did+"'>");
		sbf.append(dir.toUpperCase()+"</A></TD><TD>("+tfs+")</TD></TD>");
	    }
	}
	catch(Exception e) {
	}
	
	sbf.append("\n</TABLE>");
	return sbf;
    }

    public StringBuffer getUserHomeTree (String sid, String sub_dir, String user_name)
    {
	StringBuffer sbf = new StringBuffer("");
	sbf.append("\n<TABLE>");

	sbf.append("\n<TR>"+MyHtml.makeLinkCell("Upload File","MainBarServlet?sid="+sid+"&aid=2")+"</TR>");
	sbf.append("\n<TR>"+MyHtml.makeLinkCell("Add Folder", "MainBarServlet?sid="+sid+"&aid=1")+"</TR>");	

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    query = "SELECT ID, USER_DIR, TOTAL_FILES FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND STATUS <> -1 ORDER BY USER_DIR;";
	  
	    ArrayList alist = ejbdb.select(query);
	    // if(alist.size()>0) {
	    sbf.append("\n<TR>"+MyHtml.makeLinkCell("Edit Folder", "MainBarServlet?sid="+sid+"&aid=1-1")+"</TR>");
	    sbf.append("\n<TR>"+MyHtml.makeLinkCell("E-mail Friends", "MainBarServlet?sid="+sid+"&aid=6")+"</TR>");	
	    //}
	    sbf.append("\n<TR><TD>&nbsp;</TD></TR>");

	    Iterator it = alist.iterator();
	    ArrayList a = null;
	    String did = null;
	    String dir = null;
	    String tfs = null;
	    while (it.hasNext()) {
		a = (ArrayList)it.next();
		did = ""+a.get(0);
		dir = ""+a.get(1);
		tfs = ""+a.get(2);
		sbf.append("\n<TR><TD>&nbsp;&nbsp;<A href='MainBarServlet?sid="+sid+"&aid=3&did="+did+"'>");
		sbf.append(dir.toUpperCase()+"</A>&nbsp;["+tfs+"]</TD></TR>");
	    }
	}
	catch(Exception e) {
	}
	
	sbf.append("\n</TABLE>");
	return sbf;
    }

    public StringBuffer addFolder (HttpServletRequest request, String call_path, String mid, String sub_dir, 
				   String user_name, int user_level)
    {
	String sub     = request.getParameter("sub");
	String pass    = request.getParameter("pass");

	StringBuffer message = null;

	StringBuffer sbf = new StringBuffer("");

	if(sub != null && pass != null) {
	    String format = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwxyz-_0123456789";
	    MyUserInputCheck ck = new MyUserInputCheck();
	    if(sub.length()<1) {
		message = new StringBuffer("Please enter a name for your new forder.");
	    }

	    if(sub.length()>10) {
		return sbf;
	    }

	    if(!ck.checkFormat("[Forder Name]", sub, format)) {
		message = ck.getMessage();
	    }

	    if(pass != null && pass.length()>0) {
		if(!ck.checkFormat("[Access Code]", pass, format)) {
		    message = ck.getMessage();
		}
	    }

	    if(message == null) {
		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    query = "SELECT USER_DIR FROM USER_HOME WHERE USER_NAME='"+user_name+
			"' AND SUB_DIR='"+sub_dir+"' AND USER_DIR='"+sub+"' AND STATUS <>-1;";
		    Vector v = ejbdb.selectSingleFieldValueVector(query, "USER_DIR");
		    if(v.size()>0) {
			message = new StringBuffer("Folder ["+sub+"] exists. ");
		    }
		    else {
			query = "SELECT ID FROM USER_HOME WHERE SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+"' AND STATUS <>-1;";
			v = ejbdb.selectSingleFieldValueVector(query, "ID");
			if(v.size() >= 100) {
			    message = new StringBuffer("Total Folders exceeded limits [100].");
			}
			else {
			    query = "INSERT INTO USER_HOME (SUB_DIR, USER_NAME, USER_DIR, ACCESS_CODE, TOTAL_FILES, TOTAL_SIZE) VALUES ("+
				"'"+sub_dir+"','"+user_name+"','"+sub+"','"+pass+"', 0, 0);";
			    if(ejbdb.insert(query) != 1) {
				message = new StringBuffer("Save data error. Please try again!");
			    }
			    else {
				message = new StringBuffer ("<BR><BR><B>Folder ["+sub+"] has been added.</B><BR>");
				message.append("<B>Do you want add more folder?</B><BR>");
				message.append("\n<TABLE>");
				message.append("\n<TR>");
				message.append("\n<TD>");
				message.append("\n<FORM method='post' action='"+call_path+"'>");
				message.append("<input type='submit' name='B' value='Yes' style='font-size: 8pt'>");
				message.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
				message.append("\n<input type='hidden' name='aid' value='1-1'>");
				message.append("\n</FORM>");
				message.append("</TD>");
				message.append("\n<TD>");
				message.append("\n<FORM method='post' action='"+call_path+"'>");
				message.append("<input type='submit' name='B' value='No' style='font-size: 8pt'>");
				message.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
				message.append("\n<input type='hidden' name='aid' value='1-2'>");
				message.append("\n</FORM>");
				message.append("</TD>");
				message.append("</TR>");
				message.append("\n</TABLE>");
				return message;
			    }
			}
		    }
		}
		catch(Exception e) {
		    message = new StringBuffer("Save data error. Please try again!");
		}
	    }
	}

	sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE>");
	sbf.append("\n<TR><TD style='font-size: 14pt' align='center' colspan='3'>Add Folder</TD></TR>");
	if(message != null && message.length()>0) {
	    sbf.append("\n<TR><TD style='font-size: 10pt' align='center' colspan='3'>");
	    sbf.append("\n<img src='/images/star.gif' border='0'><I>"+message+"</I></TD></TR>");
	}
	sbf.append("\n<TR>");
	sbf.append("\n<TD style='font-size: 12pt' align='center'>Folder Name (*)</TD>");
	sbf.append("\n<TD style='font-size: 12pt' align='center'>Access code</TD>");
	sbf.append("\n<TD>&nbsp;</TD>");
	sbf.append("\n</TR>");

	if(sub == null) {
	    sbf.append("\n<TR><TD><input type='text' name='sub' value='' size='15' maxLength='10'></TD>");
	}
	else {
	    sbf.append("\n<TR><TD><input type='text' name='sub' value='"+sub+"' size='15' maxLength='10'></TD>");
	}

	if(pass == null) {
	    sbf.append("\n<TD><input type='text' name='pass' value='' size='15' maxLength='10'></TD>");
	}
	else {
	    sbf.append("\n<TD><input type='text' name='pass' value='"+pass+"' size='15' maxLength='10'></TD>");
	}

	sbf.append("\n<TD><input type='submit' name='B' value='Add' style='font-size: 8pt'></TD></TR>");
	sbf.append("\n</TABLE>");
	sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	sbf.append("\n<input type='hidden' name='aid' value='1-1'>");
	sbf.append("\n</FORM>");
	return sbf;
    }

    public StringBuffer editFolder (int sw, int sh, HttpServletRequest request, HttpServletResponse response, String mid, 
				    String sub_dir, String user_name)
    {
	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	String sub  = request.getParameter("sub");
	String pass = request.getParameter("pass");
	String did  = request.getParameter("did");
	boolean saved = false;

	StringBuffer message = null;

	StringBuffer sbf = new StringBuffer("");
	
	if(sub != null && pass != null && did != null && !did.equals("-1")) {
	    String format = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwxyz-_0123456789";
	    MyUserInputCheck ck = new MyUserInputCheck();
	    if(sub.length()<1) {
		message = new StringBuffer("Please enter a name for your new folder.");
	    }

	    if(sub.length()>10) {
		return sbf;
	    }

	    if(message == null && !ck.checkFormat("[Forder Name]", sub, format)) {
		message = ck.getMessage();
	    }

	    if(message == null && pass != null && pass.length()>0) {
		if(!ck.checkFormat("[Access Code]", pass, format)) {
		    message = ck.getMessage();
		}
	    }

	    if(message == null) {
		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    query = "SELECT USER_DIR FROM USER_HOME WHERE USER_NAME='"+user_name+
			"' AND SUB_DIR='"+sub_dir+"' AND USER_DIR='"+sub+"' AND ID <>"+did+" AND STATUS <>-1;";

		    Vector v = ejbdb.selectSingleFieldValueVector(query, "USER_DIR");
		    if(v.size()>0) {
			message = new StringBuffer("Folder ["+sub+"] exists. ");
		    }
		}
		catch(Exception e) {
		    System.out.println("UserHomeBean:editFolder:Error:"+e);
		    return (new StringBuffer("System error. Please try again later."));
		}
	    }

	    if(message == null) {
		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    query = "UPDATE USER_HOME SET USER_DIR='"+sub+"', ACCESS_CODE='"+pass+"' WHERE USER_NAME='"+user_name+
			"' AND SUB_DIR='"+sub_dir+"' AND ID="+did+" AND STATUS <> -1;"+
			"UPDATE USER_PHOTOS SET USER_DIR_NAME='"+sub+"', ACCESS_CODE='"+pass+"' WHERE USER_NAME='"+user_name+"'"+
			" AND USER_DIR_ID="+did+"";

		    if(ejbdb.update(query) == -1) {
			message = new StringBuffer("Save data error. Please try again!");
		    }
		}
		catch(Exception e) {
		    System.out.println("UserHomeBean:editFolder:Error:"+e);
		    return (new StringBuffer("System error. Please try again later."));
		}
	    }

	    if(message == null) {
		saved = true;
	    }
	}

	int table_width  = MyScreen.getWidth(sw, 700);
 
	sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE cellSpacing='0' cellPadding='3' border='1' width='"+table_width+"'>");
	sbf.append("\n<TR><TD align='center' colspan='5'><H3>Edit Folder</H3></TD></TR>");

	if(message != null && message.length()>0) {
	    sbf.append("\n<TR><TD align='center' colspan='5'>");
	    sbf.append("\n<img src='/images/star.gif' border='0'><I>"+message+"</I></TD></TR>");
	}

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    query = "SELECT ID, USER_DIR, ACCESS_CODE FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND STATUS <> -1 ORDER BY USER_DIR;";

	    ArrayList alist = ejbdb.select(query);
	    if(alist.size() >0) {
		Iterator it = alist.iterator();
		ArrayList a = null;
		while (it.hasNext()) {
		    a = (ArrayList)it.next();
		    sbf.append("<TR>");

		    if(!saved && did != null && did.equals(a.get(0))) {
			sbf.append("<TD align='center'><B>Folder Name</B></TD>");
			if(sub != null) {
			    sbf.append("<TD><input type='text' name='sub' value='"+sub+"' size='11' maxLength='10'></TD>");
			}
			else {
			    sbf.append("<TD><input type='text' name='sub' value='"+a.get(1)+"' size='11' maxLength='10'></TD>");
			}
			sbf.append("<TD align='center'><B>Access code</B></TD>");
			if(pass != null) {
			    sbf.append("<TD><input type='text' name='pass' value='"+pass+"' size='11' maxLength='10'></TD>");
			}
			else {
			    sbf.append("<TD><input type='text' name='pass' value='"+a.get(2)+"' size='11' maxLength='10'></TD>");
			}
			sbf.append("<TD align='center'><input type='submit' name='B' value='Save' style='font-size: 8pt'></TD>");
			sbf.append("\n<input type='hidden' name='did' value='"+did+"'>");
		    }
		    else {
			sbf.append("<TD align='center'><B>Folder Name</B></TD>");
			sbf.append("<TD>&nbsp;"+a.get(1)+"</TD>");
			sbf.append("<TD align='center'><B>Access code</B></TD>");
			sbf.append("<TD>&nbsp;"+a.get(2)+"</TD>");
			sbf.append(MyHtml.makeLinkCell("Edit", call_path+"?mid="+mid+"&aid=1-2&did="+a.get(0)));
		    }
		    sbf.append("</TR>");
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:editFolder:Error:"+e);
	    return (new StringBuffer("System error. Please try again later."));
	}
	sbf.append("\n</TABLE>");
	sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	sbf.append("\n<input type='hidden' name='aid' value='1-2'>");
	sbf.append("\n</FORM>");
	return sbf;
    }

    private int getTotalFiles(String dir_id) {
	int tfs = 0;
	String temp = null;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	    
	    query = "SELECT TOTAL_FILES FROM USER_HOME WHERE ID="+dir_id+" AND STATUS <> -1;";	  
	    temp = ejbdb.selectSingleFieldValue(query, "TOTAL_FILES");
	    
	    if(temp != null) {
		tfs = Integer.parseInt(temp);
	    }
	}
	catch(Exception e) {
	}
	return tfs;
    }

    public StringBuffer emailFriends (int sw, int sh, HttpServletRequest request, String mid, String table_name, 
				      String sub_dir, String user_name, String user_ip)
    {
	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	MyUserInputCheck ck = new MyUserInputCheck();
	StringBuffer message = null;
	StringBuffer error   = null;
	StringBuffer sbf = new StringBuffer("");

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }
	}
	catch(Exception e) {
	    error = new StringBuffer("Please try again!");
	}

	String email   = request.getParameter("email");
	String from    = request.getParameter("from");
	String subject = request.getParameter("subject");
	String text    = request.getParameter("text");

	String total_folders = request.getParameter("total_folders");
	Vector vsid   = null;
	Vector vemail = null;

	if(total_folders != null && email != null) {
	    String temp = null;
	    vemail = new Vector();
	    if(email.length()==0) {
		error = new StringBuffer("Please enter your friend's email.");
	    }
	    else {
		if(email.indexOf(",") != -1) {
		    email = email.replaceAll(","," ");
		}
		if(email.indexOf(";") != -1) {
		    email = email.replaceAll(";"," ");
		}
		
		StringTokenizer stk = new StringTokenizer(email);
		  
		while(stk.hasMoreTokens()) {
		    temp = stk.nextToken();
		    if(!ck.checkEmail(temp)) {
			error = new StringBuffer("E-mail format error ["+temp+"].");
			break;
		    }
		    if(!vemail.contains(temp)) {
			vemail.add(temp);
		    }
		}
	    }
	    
	    vsid = new Vector();
	    
	    for(int i=0; i<Integer.parseInt(total_folders); i++) {
		temp = request.getParameter("did_"+i);
		if(temp != null && temp.length()>0) {
		    vsid.add(temp);
		}
	    }
	    
	    if(vsid.size()==0 && error == null) {
		error = new StringBuffer("No folder has been selected.");
	    }

	    if(error == null && text != null && text.length()>2000) {
		error = new StringBuffer ("Text is too long (2000 characters or less).");
	    }

	    if(error == null) {
		StringBuffer linkbf = new StringBuffer();
		try {
		    String id = null;
		    String temp2 = null;
		    Enumeration enum = vsid.elements();
		    Vector vdb = null;
		    Object o = null;
		    String dir_list = "";

		    while(enum.hasMoreElements()) {
			id = ""+enum.nextElement();
			
			query = "SELECT E_MAIL_V FROM USER_HOME WHERE USER_NAME='"+user_name+"' AND SUB_DIR='"+sub_dir+
			    "' AND ID="+id+" AND STATUS <> -1;";
			o = ejbdb.selectSingleFieldObject(query, "E_MAIL_V");
			if(o == null) {
			    vdb = vemail;
			}
			else {
			    vdb = (Vector)o;
			    Enumeration enum1 = vemail.elements();
			    while(enum1.hasMoreElements()) {
				temp2 = (""+enum1.nextElement()).toLowerCase();
				if(!vdb.contains(temp2)) {
				    vdb.add(temp2);
				}
			    }
			}
			if(ejbdb.insertObject("UPDATE USER_HOME SET E_MAIL_V=? WHERE ID="+id+"", vdb) == -1) {
			    error = new StringBuffer("Please try again!");
			}
			dir_list +=id+"A";
		    }

		    String surl = null;
		    surl = "http://3wcenter.com"+call_path+"?mid="+mid+"&did="+dir_list;

		    // linkbf.append(surl);
		    String temp3 = null;
		    String temp4 = null;

		    Enumeration enum1 = vemail.elements();
		    while(enum1.hasMoreElements()) {
			temp3 = (""+enum1.nextElement()).toLowerCase();
			temp4 = surl+"&eid="+temp3;
			linkbf.append(temp4);
		    }
		}
		catch(Exception e) {
		    System.out.println("UserHomeBean:Error:"+e);
		    error = new StringBuffer("Please try again!");
		}

		if(error == null) {
		    String euser   = "Verification";
		    String epass    = "LiNguyen5788";

		    String to = null;
		    String content = "Please do not reply this e-mail\n"+text+"\n"+linkbf.toString();
		    if(subject == null || subject.length() == 0) {
			subject = user_name+" of 3WCenter.com";
		    }

		    try {
			SendMail smail = new SendMail();
			for(int j=0; j<vemail.size();j++) {
			    to =(String)vemail.elementAt(j);
			    if(!smail.send("usermail@3wcenter.com", euser, epass, to, subject, content)) {
				error = new StringBuffer("Sendding e-mail error to ["+to+"]. Please check your e-mail address.");
			    }
			}
		    }
		    catch (Exception e) {
			System.out.println("UserHomeBean:emailFriend:Error:["+e+"]");
			error = new StringBuffer("Sendding e-mail error. Please check your e-mail address.");
		    }     
		}

		if(error == null) {
		    message = new StringBuffer("<BR><BR><BR>");
		    if(vemail.size()>1) {
			message.append("<H3>The links have been Sent to:</H3>");
			for(int j=0; j<vemail.size();j++) {
			    message.append("<BR>"+vemail.elementAt(j));
			}
		    }
		    else {
			message.append("<H3>The link has been Sent to:</H3><BR>"+vemail.elementAt(0));
		    }
		    message.append("<BR><H3>If you are testing the link, you must sign off.</H3>");
		    return (MyMessage.tableMessage(message.toString(), 12));
		}
	    }
	}

	/////////////////////////////////////////////////////////////////////////////
	// display form
	/////////////////////////////////////////////////////////////////////////////

	sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE cellSpacing=0 cellPadding=3 border=1 width='"+MyScreen.getWidth(sw, 700)+"'>");
	sbf.append("\n<TR><TD align='center' colspan='2'>");
	sbf.append("<B>Please select folder(s) to send:</B></TD></TR>");

	if(error != null && error.length()>0) {
	    sbf.append("\n<TR><TD align='center' colspan='2'>");
	    sbf.append("\n<img src='/images/star.gif' border='0'><I>"+error+"</I></TD></TR>");
	}

	sbf.append("\n<TR><TD align='center'><B>To:</TD>");
	if(email ==null) {
	    sbf.append("\n<TD align='left'>");
	    sbf.append("<input type='text' name='email' value='' size='"+MyScreen.getWidth(sw, 80)+"' maxLength='250'></TD></TR>");
	}
	else {
	    sbf.append("\n<TD align='left'>");
	    sbf.append("<input type='text' name='email' value='"+email+"' size='"+MyScreen.getWidth(sw, 80)+"' maxLength='250'>");
	    sbf.append("</TD></TR>");
	}

	sbf.append("\n<TR><TD align='center'><B>Subject:</B></TD>");
	if(subject ==null) {
	    sbf.append("\n<TD align='left'>");
	    sbf.append("<input type='text' name='subject' value='' size='"+MyScreen.getWidth(sw, 80)+"' maxLength='80'></TD></TR>");
	}
	else {
	    sbf.append("\n<TD align='left'>");
	    sbf.append("<input type='text' name='subject' value='"+subject+"' size='"+MyScreen.getWidth(sw, 80)+"' maxLength='80'>");
	    sbf.append("</TD></TR>");
	}

	sbf.append("<TR><TD align='center'><B>Message:</B></TD><TD>");

	if(text != null) {
	    sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'>"+text+"</TEXTAREA></TD></TR>");
	}
	else {
	    sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'></TEXTAREA></TD></TR>");
	}

	try {
	    query = "SELECT ID, USER_DIR, TOTAL_FILES FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND STATUS <> -1;";
	    
	    ArrayList alist = ejbdb.select(query);
	    total_folders = ""+alist.size();
	    int m =0;
	    if(alist.size() >0) {
		Iterator it = alist.iterator();
		ArrayList a = null;
		while (it.hasNext()) {
		    a = (ArrayList)it.next();
		    sbf.append("<TR>");
		    sbf.append("<TD align='center'><B>Folder</B></TD>");

		    sbf.append("<TD align='center'>");

		    if(vsid != null && vsid.contains(a.get(0))) {
			sbf.append("<input type='checkbox' name='did_"+m+"' value='"+a.get(0)+"' checked>&nbsp;");
		    }
		    else {
			if(getTotalFiles(""+a.get(0))>0) {
			    sbf.append("<input type='checkbox' name='did_"+m+"' value='"+a.get(0)+"'>&nbsp;");
			}
			else {
			    sbf.append("<input type='checkbox' name='did_"+m+"' value='"+a.get(0)+"' disabled>&nbsp;");
			}
		    }
		    sbf.append((""+a.get(1)).toUpperCase()+"&nbsp;["+a.get(2)+"]</TD>");
		    sbf.append("</TR>");
		    m++;
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean.emailFriends:Error:"+e);
	    error = new StringBuffer("Save data error. Please try again!");
	}

	sbf.append("<TR><TD align='center' colspan='2'>&nbsp;</TD>");
	sbf.append("<TR><TD align='center' colspan='2'>");
	sbf.append("<input type='submit' name='B' value='Send' style='font-size: 8pt'></TD>");
	sbf.append("\n</TABLE>");
	sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	sbf.append("\n<input type='hidden' name='aid' value='1-4'>");
	sbf.append("\n<input type='hidden' name='total_folders' value='"+total_folders+"'>");
	sbf.append("\n</FORM>");
	return sbf;
    }

    public StringBuffer uploadFile (int sw, int sh, HttpServletRequest request,  String table_name, String sub_dir, 
				    String user_name, int user_level,  int image_size, String message)
    {
	StringBuffer sbf = new StringBuffer();	
	sbf.append("<FORM method='post' name='upload_image' ENCTYPE='multipart/form-data' action='upload'>");
	sbf.append("<TABLE>");
	sbf.append("<TR><TD align='center'><B>Upload a file from your computer to 3WCenter.com</B></TD></TR>");
	sbf.append("<TR><TD align='center'>* File size must be less than "+(image_size/1000)+"K.</TD></TR>");
	
	String error = (String)request.getAttribute("upload_error");
	if(error!= null && error.length()>1) {
	    sbf.append("<TR><TD align='center'><img src='/images/star.gif' border='0'>"+error+"</TD></TR>");
	}

	sbf.append("<TR><TD align='center'>");
	sbf.append("<INPUT TYPE='FILE' NAME='Filename' VALUE='' MAXLENGTH='255' SIZE='"+MyScreen.getWidth(sw, 77)+"' ");
	sbf.append(" style='font-size: 8pt'>");
	sbf.append("</TD>");
	sbf.append("<TR><TD align='center'>");
	sbf.append("<INPUT TYPE='SUBMIT' name='B1' Value='Attach' style='font-size: 8pt'>");
	sbf.append("</TD></TR></TABLE>");
	sbf.append("</FORM>");
	return sbf;
    }

    public StringBuffer displayAndSaveFile (int sw, int sh, HttpServletRequest request, HttpServletResponse response, String mid, 
					    String sub_dir, String user_name, int user_level, String user_ip)
    {
	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	StringBuffer sbf = new StringBuffer();	
	StringBuffer message = null;
	String folder  = request.getParameter("folder");
	String nfolder = request.getParameter("nfolder");

	String format = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwxyz-_0123456789";
	MyUserInputCheck ck = new MyUserInputCheck();

	if(nfolder != null && nfolder.length()>10) {
	    message = new StringBuffer ("New folder name is too long.");
	}
	
	if(nfolder != null && !ck.checkFormat("new forder name", nfolder, format)) {
	    message = ck.getMessage();
	}

	String pass    = request.getParameter("pass");
	if(pass != null && pass.length()>10) {
	    message = new StringBuffer ("Access code is too long.");
	}

	String title   = request.getParameter("title");
	if(title != null && title.length()>100) {
	    message = new StringBuffer ("Title is too long.");
	}

	String text    = request.getParameter("text");
	if(text != null && text.length()>501) {
	    message = new StringBuffer ("Description is too long (500 characters).");
	}

	HttpSession session  = request.getSession(true);

	if(folder == null && nfolder != null && nfolder.length()<1) {
	    message = new StringBuffer("Please enter your folder name.");
	}

	if(nfolder != null && nfolder.length()>0) {
	    folder = nfolder;
	}

	if(message == null && session.getAttribute("image_data") != null && folder != null) {
	    byte[] data = (byte[])session.getAttribute("image_data");
	    
	    int this_files  = 1;
	    int total_files = 0; //total existing files in this folder
	    long this_size  = data.length;
	    long total_size = 0; //total existing file size in this folder
	    String dir_id = null;

	    query = "SELECT TOTAL_FILES, TOTAL_SIZE FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND USER_DIR='"+folder+"' AND STATUS <> -1;";

	    try {
		if (ejbdb == null) {
		    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		}

		ArrayList a = ejbdb.selectSingleRecord(query);

		if(a == null || a.size()<1) {
		    query ="INSERT INTO USER_HOME(SUB_DIR, USER_NAME, USER_DIR, ACCESS_CODE, TOTAL_FILES, TOTAL_SIZE) VALUES("+
			"'"+sub_dir+"','"+user_name+"','"+folder+"','"+pass+"', "+this_files+","+this_size+");";

		    if(ejbdb.insert(query) != 1) {
			message = new StringBuffer("Save data error. Please try again! Error[101]");
		    }
		}
		else {
		    total_files = Integer.parseInt(""+a.get(0));
		    total_size  = Long.parseLong(""+a.get(1));
		    
		    query ="UPDATE USER_HOME SET TOTAL_FILES="+(total_files+this_files)+", TOTAL_SIZE="+(total_size+this_size)+
			" WHERE SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+"' AND  USER_DIR='"+
			folder+"' AND STATUS <> -1;";

		    if(ejbdb.update(query) != 1) {
			message = new StringBuffer("Save data error. Please try again! Error[102]");
		    }
		}

		query = "SELECT ID FROM USER_HOME WHERE SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+
		    "' AND USER_DIR='"+folder+"' AND STATUS <>-1;";
		dir_id = ejbdb.selectSingleFieldValue(query, "ID");
	    }
	    catch (Exception e) {
		message = new StringBuffer("Save data error. Please try again! Error[103]");
	    }

	    if(message == null) {
		if(title != null && title.indexOf("'") != -1) {
		    title = title.replaceAll("'","''");
		}
		if(text != null && text.indexOf("'") != -1) {
		    text = text.replaceAll("'","''");
		}
		if(title != null && title.indexOf("\"") != -1) {
		    title = title.replaceAll("\"","&quot;");
		}

		query = "INSERT INTO USER_PHOTOS(USER_NAME, SUB_DIR, USER_DIR_ID, USER_DIR_NAME,"+
		    " ACCESS_CODE, IMAGE_TITLE, IMAGE_TEXT, IMAGE, IMAGE_SIZE, IP)"+"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
		Vector vq = new Vector();
		vq.add(user_name);
		vq.add(sub_dir);
		vq.add(dir_id);
		vq.add(folder);
		vq.add(pass);
		vq.add(title);
		vq.add(text);
		vq.add(data);
		vq.add(""+data.length);
		vq.add(user_ip);

		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    if(ejbdb.insert(query, vq) != 1) {
			message = new StringBuffer("Save data error. Please try again! Error[104]");
		
			query ="UPDATE USER_HOME SET TOTAL_FILES="+total_files+", TOTAL_SIZE="+total_size+
			    " WHERE SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+"' AND  USER_DIR='"+
			    folder+"' AND STATUS <> -1;";
			ejbdb.update(query);
		    }
		    else {
			sbf.append("\n<BR>Your image has been saved.");
			vq = null;
			session.setAttribute("image_data", null);

			return(getImageList(sw, sh, request, mid, sub_dir, user_name, dir_id, ""+(total_files+1)));
		    }
		}
		catch (Exception e) {
		    System.out.println("UserHomeBean:displayAndSaveFile:Error["+e+"]");
		    message = new StringBuffer("Save data error. Please try again! Error[105]");
		}
	    }
	}

	sbf.append("\n<SCRIPT>\n");
	sbf.append("function resizeImage() {\n");
	sbf.append("   var w = document.pic.width;\n");
	sbf.append("   var h = document.pic.height;\n");
	sbf.append("   while (w>"+MyScreen.getWidth(sw, 700)+") {\n");
	sbf.append("     w = w*0.9;\n");
	sbf.append("   }\n");
	sbf.append("  document.pic.width  = w;\n");
	sbf.append("}\n");
	sbf.append("\n</SCRIPT>\n");

	sbf.append("<BR>");
	sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	sbf.append("<TABLE cellSpacing='0' cellPadding='0' border='1' width='"+MyScreen.getWidth(sw, 700)+"'>");
	sbf.append("<TR><TD align='center'>");
	sbf.append("<B>Your image has not been saved yet!</B></TD></TR>");

	if(message != null) {
	    sbf.append("<TR><TD align='center'>");
	    sbf.append("<img src=/images/star.gif boder=0>");
	    sbf.append("<I>"+message+"</I></TD></TR>");
	}

	boolean show_add_new_folder = true;

	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    query = "SELECT USER_DIR FROM USER_HOME WHERE USER_NAME='"+user_name+"' AND SUB_DIR='"+
		sub_dir+"' AND STATUS <>-1 ORDER BY USER_DIR;";
	    Vector v = ejbdb.selectSingleFieldValueVector(query, "USER_DIR");
	    Enumeration enum = v.elements();
	    if(v.size()>0) {
		sbf.append("<TR><TD align='center'><B>Save this image in folder : &nbsp;</B>");
		sbf.append("<SELECT name='folder' style='font-size:8pt' size='1'>");
		String temp = null;
		while(enum.hasMoreElements()) {
		    temp = ""+enum.nextElement();
		    if(folder != null && folder.equals(temp)) {
			sbf.append("<option value='"+temp+"' selected>"+temp.toUpperCase()+"</option>");
		    }
		    else {
			sbf.append("<option value='"+temp+"'>"+temp.toUpperCase()+"</option>");
		    }
		}
		sbf.append("</SELECT>");
		sbf.append("</TD></TR>");	
		if(v.size()>= user_level*10) {
		    show_add_new_folder = false;
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("UserHomeBean:Error:"+e);
	}

	if(show_add_new_folder) {
	    sbf.append("<TR><TD align='center'><B>Save this image in a new folder: </B>&nbsp;");
	    if(nfolder != null) {
		sbf.append("<input type='text' name='nfolder' value='"+nfolder+"' size='11' maxLength='10'>");
	    }
	    else {
		sbf.append("<input type='text' name='nfolder' value='' size='11' maxLength='10'>");
	    }
	
	    if(pass != null) {
		sbf.append("&nbsp;Access Code (Optional):&nbsp;<input type='text' name='pass' value='"+pass+"' size='11' maxLength='10'>");
	    }
	    else {
		sbf.append("&nbsp;Access Code (Optional):&nbsp;<input type='text' name='pass' size='11' maxLength='10'>");
	    }
	
	    sbf.append("</TD></TR>");
	}
	sbf.append("<TR><TD>");

	sbf.append("<TABLE border=0 width='"+MyScreen.getWidth(sw, 700)+"'>");
	sbf.append("<TR><TD>Title: (Optional)</TD><TD>");
	if(title != null) {
	    sbf.append("<input type='text' name='title' value=\""+title+"\" size='"+MyScreen.getWidth(sw, 77)+"' ");
	    sbf.append(" maxLength='100'></TD></TR>");
	}
	else {
	    sbf.append("<input type='text' name='title' size='"+MyScreen.getWidth(sw, 77)+"' maxLength='100'></TD></TR>");
	}
	sbf.append("<TR><TD>Description:<BR>(Optional)</TD><TD>");
	if(text != null) {
	    sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'>"+text+"</TEXTAREA></TD></TR>");
	}
	else {
	    sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'></TEXTAREA></TD></TR>");
	}
	sbf.append("</TABLE>");
	sbf.append("</TD></TR>");
	sbf.append("<TR><TD align='center'>");
	sbf.append("<input type='submit' name='B1' value='Save' style='font-size: 8pt'>");
	sbf.append("<input type='reset' name='B2' value='Reset' style='font-size: 8pt'>");
	sbf.append("</TD></TR>");
	sbf.append("</TABLE>");

	sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	sbf.append("\n<input type='hidden' name='aid' value='1-3-1'>");
	sbf.append("\n</FORM>");
	sbf.append("<BR>");
	sbf.append("<TABLE cellSpacing='0' cellPadding='0' border='1' width='"+MyScreen.getWidth(sw, 700)+"'");
	sbf.append(" height='"+MyScreen.getHeight(sh, 500)+"'>");
	sbf.append("<TR><TD align='center'>");
	sbf.append("<img name=pic src=ShowImageServlet onLoad=javascript:resizeImage();>");
	sbf.append("</TD></TR>");
	sbf.append("</TABLE>");
	return sbf;
    }

    public StringBuffer getImageList(int sw, int sh, HttpServletRequest request, String mid, 
				     String sub_dir, String user_name) {
	String did = request.getParameter("did");
	String iid = request.getParameter("iid");
	return getImageList(sw, sh, request, mid, sub_dir, user_name, did, iid);
    }

    public StringBuffer getImageList(int sw, int sh, HttpServletRequest request, String mid, String sub_dir, 
				     String user_name, String did, String iid) {
	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	StringBuffer sbf = new StringBuffer("");
	HttpSession session  = request.getSession(true);
	ArrayList alist = null;
	String error = null;

	query = "SELECT ID, IMAGE_TITLE, IMAGE_TEXT FROM USER_PHOTOS WHERE SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+
	    "' AND USER_DIR_ID='"+did+"';";
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    alist = ejbdb.select(query);
	    if(alist.size()<1) {
		return (new StringBuffer("<BR><BR><H3>No File In This Folder!</H3>"));
	    }
	
       
	    Iterator it = alist.iterator();
	    ArrayList a = null;
	    String[] file_list  = new String[alist.size()];
	    String[] file_title = new String[alist.size()];
	    String[] file_capt  = new String[alist.size()];
	    int m =0;
	    while (it.hasNext()) {
		a = (ArrayList)it.next();
		file_list  [m]  = ""+a.get(0);
		file_title [m]  = ""+a.get(1);
		file_capt  [m]  = ""+a.get(2);
		m++;
	    }

	    if(iid == null || Integer.parseInt(iid) > file_list.length) {
		iid = "1";
	    }

	    int c = Integer.parseInt(iid);

	    int n = c+1;
	    if(n == file_list.length+1) {
		n = 1;
	    }
	    int b = c -1;
	    if(b == 0) {
		b = file_list.length;
	    }

	    int table_width  = MyScreen.getWidth(sw, 700);
	    int table_height = MyScreen.getHeight(sh, 500);

	    sbf.append("\n<SCRIPT>\n");
	    sbf.append("function resizeImage() {\n");
	    sbf.append("   var w = document.pic.width;\n");
	    sbf.append("   var h = document.pic.height;\n");
	    sbf.append("   while (w>"+table_width+") {\n");
	    sbf.append("     w = w*0.9;\n");
	    sbf.append("   }\n");
	    sbf.append("  document.pic.width  = w;\n");
	    sbf.append("}\n");
	    sbf.append("\n</SCRIPT>\n");
	    
	    sbf.append("\n<TABLE align='center'>");
	    sbf.append("\n<TR>");
	    sbf.append(MyHtml.makeLinkCell("Prev.", call_path+"?mid="+mid+"&aid=3&did="+did+"&iid="+b+""));
	    sbf.append("<TD style='color:#FFFFFF'>["+c+"/"+file_list.length+"]</TD>");
	    sbf.append(MyHtml.makeLinkCell("Next", call_path+"?mid="+mid+"&aid=3&did="+did+"&iid="+n+""));
	    sbf.append("\n</TR>");
	    sbf.append("\n</TABLE>");
	    
	    sbf.append("\n<TABLE border='1' width='"+table_width+"'>");
	    if(file_title[c-1].length()>0) {
		sbf.append("\n<TR><TD align='center'><B>"+file_title[c-1]+"</B></TD></TR>");
	    }
	
	    sbf.append("\n<TR><TD align='center' width='"+table_width+"' height='"+table_height+"'>");

	    session.setAttribute("siid",file_list[c-1]);
	    sbf.append("\n<img name='pic' src='ShowImageServlet?iid="+file_list[c-1]+"&fid=11&tid=1' border='0'");

	    if(file_capt[c-1].length()>0) {
		sbf.append(" alt='"+file_capt[c-1]+"' ");
	    }
	    sbf.append(" onLoad='javascript:resizeImage();'>");

	    sbf.append("\n</TD></TR>");
	    sbf.append("\n</TABLE>");

	    sbf.append("\n<TABLE align='center'>");
	    sbf.append("\n<TR>");
	    sbf.append(MyHtml.makeLinkCell("Delete", call_path+"?mid="+mid+"&aid=3-2&did="+did+"&iid="+file_list[c-1]));
	    sbf.append(MyHtml.makeLinkCell("Edit", call_path+"?mid="+mid+"&aid=3-3&did="+did+"&iid="+file_list[c-1]));
	    sbf.append("\n</TR>");
	    sbf.append("\n</TABLE>");

	    return sbf;
	}
	catch (Exception e) {
	    System.out.println("UserHomeBean:getImageList:"+e);
	    return (new StringBuffer("Please try again later!"));
	}
    }

    public StringBuffer displayUserImage(int sw, int sh, HttpServletRequest request, String mid, 
					 String sub_dir, String user_name, int user_level) {
	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	StringBuffer sbf = new StringBuffer();
	HttpSession session  = request.getSession(true);
	int table_width  = MyScreen.getWidth(sw, 700);
	int table_height = MyScreen.getHeight(sh, 500);

	sbf.append("\n<TABLE>");
	sbf.append("\n<TR>");
	sbf.append(MyHtml.makeLinkCell("Prev.", call_path+"?mid="+mid));
	sbf.append("<TD style='color:#FFFFFF; font-size:10pt'>[1/1]</TD>");
	sbf.append(MyHtml.makeLinkCell("Next", call_path+"?mid="+mid));
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");

	sbf.append("\n<TABLE border='1' width='"+table_width+"'>");
	sbf.append("\n<TR><TD align='center'><B>Sample Image</B></TD></TR>");
	
	sbf.append("\n<TR><TD align='center' width='"+table_width+"' height='"+table_height+"'>");
	session.setAttribute("siid","453");
	sbf.append("\n<img name='pic' src='ShowImageServlet?iid=142&fid=11&tid=1' border='0'");
	sbf.append(" alt='Image text.' width='"+table_width+"'>");
	sbf.append("\n</TD></TR>");
	sbf.append("\n</TABLE>");

	sbf.append("\n<TABLE>");
	sbf.append("\n<TR>");
	sbf.append(MyHtml.makeLinkCell("Delete", call_path+"?mid="+mid));
	sbf.append(MyHtml.makeLinkCell("Edit", call_path+"?mid="+mid));
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");

	return sbf;
    }

    public StringBuffer getGuestImageList(int sw, int sh, HttpServletRequest request, HttpSession session, String mid) {
	try {
	    //String call_path   = request.getServletPath();
	    String call_path     = request.getContextPath()+request.getServletPath();

	    StringBuffer error = new StringBuffer("");
	    StringBuffer sbf   = new StringBuffer("");

	    String dids  = request.getParameter("did");
	    String email = request.getParameter("eid");

	    Hashtable image_hs = (Hashtable)session.getAttribute("image_hs");

	    if(image_hs == null && dids != null && email != null) {	
		MyUserInputCheck ck = new MyUserInputCheck();
		if(!ck.checkEmail(email)) {
		    System.out.println("UserHomeBean:Error:[chechEmial]");
		    return error;
		}
		if(dids == null || dids.indexOf("A")==-1) {
		    System.out.println("UserHomeBean:Error:[dids==null]");
		    return error;
		}

		//=============================================
		// check guest email is in user's list
		//=============================================

		String id = null;
		ArrayList alist = null;
		StringTokenizer stk = new StringTokenizer(dids, "A");
		Vector v = null;
		Vector vid = new Vector();
		image_hs = new Hashtable();
		int k =0;
		while(stk.hasMoreTokens()) {
		    id = stk.nextToken();
		    query = "SELECT E_MAIL_V FROM USER_HOME WHERE ID="+id+";";
		    
		    try {
			if (ejbdb == null) {
			    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
			}

			Object o = ejbdb.selectSingleFieldObject(query, "E_MAIL_V");
			if(o == null) {
			    System.out.println("UserHomeBean:Error:[o==null]");
			    return error;
			}
			v = (Vector)o;
			if(!v.contains(email)) {
			    System.out.println("UserHomeBean:Error:[v.contains(email)]");
			    return error;
			}

			vid.add(id);
			query = "SELECT ID, IMAGE_TITLE, IMAGE_TEXT, USER_DIR_NAME FROM USER_PHOTOS WHERE USER_DIR_ID="+id+";";
			image_hs.put(""+k, ejbdb.select(query));
			k++;
		    }
		    catch (Exception e) {
			System.out.println("UserHomeBean:getImageList:"+e);
			return (new StringBuffer("Please try again later!"));
		    }
		}
	    
		StringBuffer qbf = new StringBuffer("SELECT USER_DIR FROM USER_HOME WHERE (");
		Enumeration enum = vid.elements();
		int m=0;
		while(enum.hasMoreElements()) {
		    m++;
		    qbf.append("ID="+enum.nextElement());
		    if(m != vid.size()) {
			qbf.append(" OR ");
		    }
		}
		qbf.append(");");
	
		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    Vector viid = ejbdb.selectSingleFieldValueVector(qbf.toString(), "USER_DIR");
		    if(viid == null || viid.size()==0) {
			System.out.println("UserHomeBean:Error:[viid==null]");
			return error;
		    }
		    
		    image_hs.put("dids",viid);
		}
		catch (Exception e) {
		    System.out.println("UserHomeBean:getImageList:"+e);
		    return (new StringBuffer("Please try again later!"));
		}
	    
		session.setAttribute("image_hs",image_hs);
	    }
	    else {
		image_hs = (Hashtable)session.getAttribute("image_hs");
	    }
	    
	    String hid = request.getParameter("hid");
	    if(hid == null) {
		hid = "0";
	    }

	    if(image_hs == null || !image_hs.containsKey(hid)) {
		System.out.println("UserHomeBean:Error:[image_hs.containsKey]["+image_hs+"]");
		return error;
	    }

	    StringBuffer leftbf = new StringBuffer();

	    leftbf = new StringBuffer("<BR><BR><BR><BR><BR>");
	    leftbf.append("<TABLE>");
	    
	    Vector vdirs = (Vector)image_hs.get("dids");
	    Enumeration enum = vdirs.elements();
	    String temp = null;
	    int nn=0;
	    while(enum.hasMoreElements()) {
		temp = ""+enum.nextElement();
		temp = temp.trim();
		leftbf.append("<TR>"+MyHtml.makeLinkCell(temp, call_path+"?mid="+mid+"&hid="+nn)+"</TR>");
		nn++;
	    }

	    leftbf.append("</TABLE>");

	    ArrayList alist = (ArrayList)image_hs.get(hid);
	    String[] file_list  = new String[alist.size()];
	    String[] file_title = new String[alist.size()];
	    String[] file_capt  = new String[alist.size()];
	    String[] dir_names  = new String[alist.size()];
	    ArrayList a = null;
	    Iterator it = alist.iterator();
	    int m =0;
	    while (it.hasNext()) {
		a = (ArrayList)it.next();
		file_list[m]  = ""+a.get(0);
		file_title[m] = ""+a.get(1);
		file_capt[m]  = ""+a.get(2);
		dir_names[m]  = ""+a.get(3);
		m++;
	    }

	    String iid = request.getParameter("iid");

	    if(iid == null) {
		iid = "1";
	    }
	    
	    int c = Integer.parseInt(iid);
	    int n = c+1;
	    if(n == file_list.length+1) {
		n = 1;
	    }
	    int b = c -1;
	    if(b == 0) {
		b = file_list.length;
	    }
	
	    sbf.append("\n<SCRIPT>\n");
	    sbf.append("function resizeImage() {\n");
	    sbf.append("   var w = document.pic.width;\n");
	    sbf.append("   var h = document.pic.height;\n");
	    sbf.append("   while (w>"+MyScreen.getWidth(sw,700)+") {\n");
	    sbf.append("     w = w*0.9;\n");
	    sbf.append("   }");
	    sbf.append("  document.pic.width  = w;\n");
	    sbf.append("}\n");
	    sbf.append("\n</SCRIPT>\n");
	
	    sbf.append("<CENTER>");

	    StringBuffer pnsbf = new StringBuffer();
	    pnsbf.append("\n<TABLE cellSpacing='0' cellPadding='0' border='0' width='100%'>");
	    pnsbf.append("<TR><TD align='center'>");
	    pnsbf.append("\n<TABLE>");
	    pnsbf.append("\n<TR>");
	    pnsbf.append(MyHtml.makeLinkCell("Prev.", call_path+"?mid="+mid+"&hid="+hid+"&iid="+b));
	    pnsbf.append("<TD>["+c+"/"+file_list.length+"]</TD>");
	    pnsbf.append(MyHtml.makeLinkCell("Next", call_path+"?mid="+mid+"&hid="+hid+"&iid="+n));
	    pnsbf.append("\n</TR>");
	    pnsbf.append("\n</TABLE>");
	    pnsbf.append("\n</TD></TR>");
	    pnsbf.append("\n</TABLE>");
	    
	    sbf.append(pnsbf);
	    sbf.append("\n<TABLE border='1' width='"+MyScreen.getWidth(sw, 700)+"'>");
	    sbf.append("\n<TR><TD align='center'>"+dir_names[c-1]+"</TD></TR>");
	    if(file_title[c-1].length()>0) {
		sbf.append("\n<TR><TD align='center'><B>"+file_title[c-1]+"</B></TD></TR>");
	    }
	
	    sbf.append("\n<TR><TD align='center' width='"+MyScreen.getWidth(sw, 700)+"' height='"+MyScreen.getHeight(sh, 500)+"'>");
	    session.setAttribute("siid", file_list[c-1]);
	    sbf.append("\n<img name='pic' src='ShowImageServlet?iid="+file_list[c-1]+"&fid=11&tid=1' border='0'");

	    if(file_capt[c-1].length()>0) {
		sbf.append(" alt='"+file_capt[c-1]+"' ");
	    }

	    sbf.append(" onLoad='javascript:resizeImage();'>");
	    sbf.append("\n</TD></TR>");
	    sbf.append("\n</TABLE>");
	    sbf.append(pnsbf);
	    sbf.append("</CENTER>");
	    return (MyHtml.forumDisplay(leftbf, sbf, new StringBuffer("&nbsp;")));
	}
	catch (Exception e) {
	    System.out.println("UserHomeBean:getGuestImage:Error:Exception:"+e);
	    return (ErrorPageBean.errorTable(request, "Page not found!"));
	}
    }

    public boolean deleteFile(HttpServletRequest request, String table_name, String sub_dir, String user_name) {
	String iid = request.getParameter("iid");
	String did = request.getParameter("did");
	
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    query = "SELECT TOTAL_FILES, TOTAL_SIZE FROM USER_HOME WHERE USER_NAME='"+user_name+
		"' AND SUB_DIR='"+sub_dir+"' AND ID='"+did+"' AND STATUS <> -1;";
	    ArrayList a = ejbdb.selectSingleRecord(query);
	    if(a.size() != 2) {
		return false;
	    }

	    int total_files = Integer.parseInt(""+a.get(0));
	    long total_size = Long.parseLong(""+a.get(1));

	    query = "SELECT IMAGE_SIZE FROM "+table_name+" WHERE ID="+iid+" AND USER_DIR_ID="+did+
		" AND SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+"';";
	    String image_size = ejbdb.selectSingleFieldValue(query, "IMAGE_SIZE");
	    if(image_size == null || image_size.length()<1) {
		return false;
	    }

	    query = "DELETE FROM "+table_name +" WHERE ID="+iid+" AND USER_DIR_ID="+did+
		" AND SUB_DIR='"+sub_dir+"' AND USER_NAME='"+user_name+"';";
	   
	    if(ejbdb.delete(query)==1) {
		query = "UPDATE USER_HOME SET TOTAL_FILES="+(total_files-1)+", TOTAL_SIZE="+(total_size - Long.parseLong(image_size))+
		   " WHERE USER_NAME='"+user_name+"' AND SUB_DIR='"+sub_dir+"' AND ID='"+did+"' AND STATUS <> -1;";
		ejbdb.update(query);
		return true;
	    }
	    else {
		return false;
	    }
	}
	catch (Exception e) {
	    System.out.println("UserHomeBean:deleteFile:"+e);
	    return false;
	}
    }

    public StringBuffer editAndSaveFile(int sw, int sh, HttpServletRequest request, String mid, 
					String table_name, String sub_dir, String user_name) {

	//String call_path = request.getServletPath();
	String call_path     = request.getContextPath()+request.getServletPath();

	String iid = request.getParameter("iid");
	String did = request.getParameter("did");

	StringBuffer sbf = new StringBuffer();	
	StringBuffer message = null;

	String title   = request.getParameter("title");
	String text    = request.getParameter("text");

	if(title != null && title.length()>100) {
	    message = new StringBuffer ("Title is too long.");
	}

	if(title != null && title.indexOf("\"") != -1) {
	    title = title.replaceAll("\"","&quot;");
	}

	if(message == null && text != null && text.length()>501) {
	    message = new StringBuffer ("Description is too long (500 characters).");
	}

	int table_width = MyScreen.getWidth(sw, 700);
	sbf.append("\n<SCRIPT>\n");
	sbf.append("function resizeImage() {\n");
	sbf.append("   var w = document.pic.width;\n");
	sbf.append("   var h = document.pic.height;\n");
	sbf.append("   while (w>"+table_width+") {\n");
	sbf.append("     w = w*0.9;\n");
	sbf.append("   }\n");
	sbf.append("  document.pic.width  = w;\n");
	sbf.append("}\n");
	sbf.append("\n</SCRIPT>\n");

	sbf.append("<BR>");
	
	ArrayList a = null;
	boolean saved = false;
	try {
	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    if(title == null && text == null) {
		query = "SELECT IMAGE_TITLE, IMAGE_TEXT FROM USER_PHOTOS WHERE USER_NAME='"+
		    user_name+"' AND SUB_DIR='"+sub_dir+"' AND USER_DIR_ID="+did+" AND ID="+iid+";";
		a = ejbdb.selectSingleRecord(query);
	    }
	    else {
		if(message == null) {
		    if(title != null && title.indexOf("'") != -1) {
			title = title.replaceAll("'","''");
		    }
		    if(text != null && text.indexOf("'") != -1) {
			text = text.replaceAll("'","''");
		    }

		    query = "UPDATE USER_PHOTOS SET IMAGE_TITLE='"+title+"', IMAGE_TEXT='"+text+"' WHERE USER_NAME='"+
		    user_name+"' AND SUB_DIR='"+sub_dir+"' AND USER_DIR_ID="+did+" AND ID="+iid+";";
		    if(ejbdb.update(query)==1) {
			return(getImageList(sw, sh, request, mid, sub_dir, user_name, did, iid));
		    }
		}
	    }
	}
	catch(Exception e) {
	    message = new StringBuffer ("Save data error.");
	}

	if(!saved) {
	    sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	    sbf.append("<TABLE cellSpacing='0' cellPadding='0' border='1' width='"+table_width+"'>");

	    if(message != null) {
		sbf.append("<TR><TD align='center' colspan='2'>");
		sbf.append("<img src=/images/star.gif boder=0>");
		sbf.append("<I>"+message+"</I></TD></TR>");
	    }
	    sbf.append("<TR><TD>");
	    sbf.append("<TABLE border=0 width='"+table_width+"'>");
	    sbf.append("<TR><TD><B>Title:</B>(Optional)</TD><TD>");

	    if(title != null) {
		sbf.append("<input type='text' name='title' value=\""+title+"\" ");
		sbf.append(" size='"+MyScreen.getWidth(sw, 77)+"' maxLength='100'>");
		sbf.append("</TD></TR>");
	    }
	    else {
		sbf.append("<input type='text' name='title' value=\""+a.get(0)+"\" ");
		sbf.append(" size='"+MyScreen.getWidth(sw, 77)+"' maxLength='100'>");
		sbf.append("</TD></TR>");
	    }

	    sbf.append("<TR><TD><B>Description:</B><BR>(Optional)</TD><TD>");
	    if(text != null) {
		sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'>"+text+"</TEXTAREA></TD></TR>");
	    }
	    else {
		sbf.append("<TEXTAREA name='text' rows='5' cols='"+MyScreen.getWidth(sw, 55)+"'>"+a.get(1)+"</TEXTAREA></TD></TR>");
	    }
	    sbf.append("</TABLE>");

	    sbf.append("</TD></TR>");
	    sbf.append("<TR><TD align='center'>");
	    sbf.append("<input type='submit' name='B1' value='Save' style='font-size: 8pt'>");
	    sbf.append("<input type='reset' name='B2' value='Reset' style='font-size: 8pt'>");
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");
	    
	    sbf.append("\n<input type='hidden' name='mid' value='"+mid+"'>");
	    sbf.append("\n<input type='hidden' name='aid' value='3-3'>");
	    sbf.append("\n<input type='hidden' name='iid' value='"+iid+"'>");
	    sbf.append("\n<input type='hidden' name='did' value='"+did+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("<BR>");

	    sbf.append("<TABLE border='1' width='"+table_width+"' height='"+MyScreen.getHeight(sh, 400)+"'>");
	    sbf.append("<TR><TD align='center'>");
	    sbf.append("<img name=pic src=ShowImageServlet?iid="+iid+"&fid=11&tid=1 onLoad=javascript:resizeImage();>");
	    sbf.append("</TD></TR>");
	    sbf.append("</TABLE>");
	}
	return sbf;
    }

    public static boolean isManager(HttpServletRequest request, String username, String dim) {
	HttpSession session  = request.getSession(true);
	Hashtable dir_hs = (Hashtable)session.getAttribute("ContralOpenClose");
	if(dir_hs != null) {
	    String sid = request.getParameter("sid");
	    String manager_str = ""+dir_hs.get(sid+"_manager");
	    if(username == null || username.length()<1 || manager_str == null || manager_str.length()<1) {
		return false;
	    }

	    if(manager_str.indexOf(dim) == -1) {
		return(username.equalsIgnoreCase(manager_str));
	    }
	    else {
		StringTokenizer stk = new StringTokenizer(manager_str, dim);
		while(stk.hasMoreTokens()) {
		    if(username.equalsIgnoreCase(stk.nextToken())) {
			return true;
		    }
		}
	    }
	}
	return false;
    }

    public static StringBuffer resetUrl (String url) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<HTML><HEAD>");
	sbf.append("\n<TITLE>user sign in</TITLE>");
	sbf.append("\n</HEAD>");
	sbf.append("\n<SCRIPT>");
	sbf.append("function DoLogIn() {");
	sbf.append("  top.location.replace(\""+url+"\");");
	sbf.append("  return true;");
	sbf.append("}");
	sbf.append("\n</SCRIPT>");
	sbf.append("\n<BODY onLoad=DoLogIn();>");
	sbf.append("\n</BODY></HTML>");
	return sbf;
    }
}






